%% Ex 5

% a)
 %{
  pSS = 0.7;
  pSN = 0.2;
  pSC = 0.1;

  pNS = 0.2;
  pNN = 0.3;
  pNC = 0.5;

  pCS = 0.3;
  pCN = 0.3;
  pCC = 0.4;

  T = [pSS pNS pCS ; pSN pNN pCN ; pSC pNC pCC] %SOL NUVENS CHUVA
  %}
  %% OU
  
  %Apercebendo-nos que a matriz T e a transposta dadada:
  T = [0.7 0.2 0.1 ; 0.2 0.3 0.5 ; 0.3 0.3 0.4].'

% b)
  %pij(29) -> i = nao faltar ; j = nao faltar


  x0 = [1 ; 0 ; 0]; %SOL ; NUVENS ; CHUVA
  x2 = T^2 * x0;
  printf("Probabilidade de, estando sol na observacao inicial, o dia 2 ser de chuva = %f\n",x2(3));

% c)
  %{
  pSS = zeros(1,20);
  pSN = zeros(1,20);
  pSC = zeros(1,20);

  pNS = zeros(1,20);
  pNN = zeros(1,20);
  pNC = zeros(1,20);

  pCS = zeros(1,20);
  pCN = zeros(1,20);
  pCC = zeros(1,20);
  
  figure(1);
  hold on;
  
  for n = 1 : 20
      Temp = T^n
      pSS(n) = Temp(1,1);
      pSN(n) = Temp(1,2);
      pSC(n) = Temp(1,3);

      pNS(n) = Temp(2,1);
      pNN(n) = Temp(2,2);
      pNC(n) = Temp(2,3);

      pCS(n) = Temp(3,1);
      pCN(n) = Temp(3,2);
      pCC(n) = Temp(3,3);
  endfor
  
  plot(1:20,pSS,'LineWidth',2);
  plot(1:20,pSN,'LineWidth',2);
  plot(1:20,pSC,'LineWidth',2);

  plot(1:20,pNS,'LineWidth',2);
  plot(1:20,pNN,'LineWidth',2);
  plot(1:20,pNC,'LineWidth',2);

  plot(1:20,pCS,'LineWidth',2);
  plot(1:20,pCN,'LineWidth',2);
  plot(1:20,pCC,'LineWidth',2);

  xlabel("n");
  ylabel("Prob.");  
  legend('pSS','pSN','pSC','pNS','pNN','pNC','pCS','pCN','pCC');
  %}
  
  M = [];
  for n = 1 : 20
    Tn = T^n;
    M = [M Tn(:)];
  end
  
  plot(1:20,M,'LineWidth',2);

  xlabel("n");
  ylabel("Prob.");  
  legend('pSS','pSN','pSC','pNS','pNN','pNC','pCS','pCN','pCC');
  
% d)
  figure(2);
  
  M = [];
  n = 1;
  while true
    Tn = T^n;
    if max(abs(Tn - T^(n-1))) < 10^(-4) && n>1
      break
    end
    M = [M Tn(:)];
    n = n+1;
   end
  
  plot(1:n-1,M,'LineWidth',2);

  xlabel("n");
  ylabel("Prob.");  
  legend('pSS','pSN','pSC','pNS','pNN','pNC','pCS','pCN','pCC');
  